package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.adapter.CartListAdapter;
import com.nest.WorkNest.adapter.CartListAdapter.onCheckedChanged;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.data.CartData;
import com.nest.WorkNest.entity.ProductDetailCart;
import com.nest.WorkNest.tools.ParseUtils;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.view.ListViewForScrollView;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ShoppingCartAct extends BaseActivity implements onCheckedChanged, OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private ListViewForScrollView lv_shoppingcart;
    private Context context = ShoppingCartAct.this;
    private CartListAdapter cAdapter;
    private Button btn_shoppingcart_pay;
    private CheckBox chk_shoppingcart_all;
    private TextView tv_shoppingcart_allprice;
    private LinearLayout ll_shoppingcart_allin;
    private List<String> ChoiceList = new ArrayList<>();
    private SwipeRefreshLayout mSwipeLayout;
    private ProductDetailCart productDetailCart;
    private String productId, id, productType, productName, productimgUrl;
    private HashMap<String, String> productdata = new HashMap<>();
    private HashMap<String, String> bulkOrder = new HashMap<>();
    private ArrayList<HashMap<String, String>> numList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_cart);
        loadShoppingCart();
        initView();

    }

    private void initView() {
        initBar();
        initProgress(context, "加载中...");
        productDetailCart = new ProductDetailCart();
        actionbar_side_tab_name.setVisibility(View.VISIBLE);
        actionbar_side_tab_name.setText(getResources().getString(R.string.main_tab_text4));
        tv_actionbar_tab_side_right.setVisibility(View.VISIBLE);
        lv_shoppingcart = (ListViewForScrollView) findViewById(R.id.lv_shoppingcart);
        btn_shoppingcart_pay = (Button) findViewById(R.id.btn_shoppingcart_pay);
        tv_shoppingcart_allprice = (TextView) findViewById(R.id.tv_shoppingcart_allprice);
        chk_shoppingcart_all = (CheckBox) findViewById(R.id.chk_shoppingcart_allin);
        ll_shoppingcart_allin = (LinearLayout) findViewById(R.id.ll_shoppingcart_allin);
        cAdapter = new CartListAdapter(context, CartData.arrayList_cart);
        cAdapter.setOnCheckedChanged(this);
        btn_shoppingcart_pay.setOnClickListener(this);
        lv_shoppingcart.setSelector(R.color.bg_transparent);
        lv_shoppingcart.setAdapter(cAdapter);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.rl_modulename_refresh);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
//        lv_shoppingcart.setOnItemClickListener(new OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                startActivity(new Intent(context, ProductDetailAct.class));
//            }
//        });
        tv_actionbar_tab_side_right.setOnClickListener(this);
        chk_shoppingcart_all.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int isChoice_all = 0;
                if (isChecked) {
                    for (int i = 0; i < lv_shoppingcart.getCount(); i++) {
                        // 如果选中了全选，那么就将列表的每一行都选中
                        ((CheckBox) (lv_shoppingcart.getChildAt(i))
                                .findViewById(R.id.chk_order_chooseitems)).setChecked(true);
                    }
                } else {
                    for (int i = 0; i < lv_shoppingcart.getCount(); i++) {
                        // 判断列表每一行是否处于选中状态，如果处于选中状态，则计数+1
                        if (((CheckBox) (lv_shoppingcart.getChildAt(i))
                                .findViewById(R.id.chk_order_chooseitems)).isChecked()) {
                            // 计算出列表选中状态的数量
                            isChoice_all += 1;
                        }
                    }
                    if (isChoice_all == CartData.arrayList_cart.size()) {

                        for (int i = 0; i < CartData.arrayList_cart.size(); i++) {
                            // 列表每一行都取消
                            ((CheckBox) (lv_shoppingcart.getChildAt(i))
                                    .findViewById(R.id.chk_order_chooseitems)).setChecked(false);
                        }
                    }
                }

            }
        });
    }


    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            showToast("再按一次退出程序");
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    public void getChoiceData(int position, boolean isChoice) {
        // 得到点击的哪一行
        if (isChoice) {
            if (CartData.arrayList_cart.size() != 0) {
                String[] num = new String[]{
                        CartData.arrayList_cart.get(position).get("perPrice"),
                        CartData.arrayList_cart.get(position).get("totalQuantity")};
                CartData.Allprice_cart += ParseUtils
                        .string2float(ParseUtils.multiplyFloatString(num));
            }
        } else {
            if (CartData.arrayList_cart.size() != 0) {
                String[] num = new String[]{
                        CartData.arrayList_cart.get(position).get("perPrice"),
                        CartData.arrayList_cart.get(position).get("totalQuantity")};
                BigDecimal b1 = new BigDecimal(Float.toString(CartData.Allprice_cart));
                BigDecimal b2 = new BigDecimal(Float.toString(ParseUtils
                        .string2float(ParseUtils.multiplyFloatString(num))));
                CartData.Allprice_cart = b1.subtract(b2).floatValue();
            }
        }
        // 记录列表处于选中状态的数量
        int num_choice = 0;
        ChoiceList.clear();
        for (int i = 0; i < CartData.arrayList_cart.size(); i++) {
            // 判断列表中每一行的选中状态，如果是选中，计数加1
            if (null != lv_shoppingcart.getChildAt(i) && ((CheckBox) (lv_shoppingcart.getChildAt(i))
                    .findViewById(R.id.chk_order_chooseitems)).isChecked()) {
                // 列表处于选中状态的数量+1
                num_choice += 1;
                ChoiceList.add(i + "");
            }
        }
        // 判断列表中的CheckBox是否全部选择
        if (num_choice == CartData.arrayList_cart.size()) {
            // 如果选中的状态数量=列表的总数量，那么就将全选设置为选中
            chk_shoppingcart_all.setChecked(true);
        } else {
            // 如果选中的状态数量！=列表的总数量，那么就将全选设置为取消
            chk_shoppingcart_all.setChecked(false);
        }
        tv_shoppingcart_allprice.setText("￥" + CartData.Allprice_cart + "");
//        for (int k = 0; k < ChoiceList.size(); k++) {
//        }
    }

    public void editableFalse() {
        tv_actionbar_tab_side_right.setText("编辑");
        ll_shoppingcart_allin.setVisibility(View.VISIBLE);
        CartData.editable = false;
    }

    @Override
    protected void onResume() {
        editableFalse();
        loadShoppingCart();
        super.onResume();
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeLayout.setRefreshing(false);
                loadShoppingCart();
            }
        }, 2000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_actionbar_tab_side_right:
                if (CartData.editable) {
                    editableFalse();
                } else {
                    tv_actionbar_tab_side_right.setText("完成");
                    for (int i = 0; i < CartData.arrayList_cart.size(); i++) {
                        ((CheckBox) (lv_shoppingcart.getChildAt(i))
                                .findViewById(R.id.chk_order_chooseitems)).setChecked(false);
                    }
                    CartData.Allprice_cart = 0;
                    ll_shoppingcart_allin.setVisibility(View.INVISIBLE);
                    CartData.editable = true;
                }
                cAdapter.notifyDataSetChanged();
                break;
            case R.id.chk_orderedit_allin:

                break;
            case R.id.btn_shoppingcart_pay:
                if (ChoiceList.size() > 1) {
                    showToast("当前仅支持单件结算");
                } else if (ChoiceList.size() == 1) {
                    if (!TextUtils.isEmpty(ChoiceList.get(0))) {
                        int position = ParseUtils.string2int(ChoiceList.get(0));
                        productId = CartData.arrayList_cart.get(position).get("productId");
                        id = CartData.arrayList_cart.get(position).get("id");
                        productimgUrl = CartData.arrayList_cart.get(position).get("mainImage");
                        loadProductDetail(productId);
                    }
                }
                break;
        }
    }

    private void loadShoppingCart() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.json(result);
                JSONObject jsonObject = Tool.getJsonObject(result);
                JSONArray jsonArray;
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    jsonArray = Tool.getJsonArray(result, "datalist");
                    CartData.arrayList_cart = Tool.getListMapByJsonArray(jsonArray);
                    cAdapter.update(CartData.arrayList_cart);
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostShoppingCart(context, ioAuthCallBack);
    }

    public void loadqueryShoppingCartRecords(String id) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.json(result);
                if (Tool.getString(result, "resultCode").equals("0")) {
                    bulkOrder = Tool.getMapByJsonObj(Tool.getString(result, "bulkOrder"));
                    numList = Tool.getListMapByJsonArray(Tool.getJsonArray(result, "numList"));
                    productDetailCart.setGetdatalist(numList);
                    Logger.d(bulkOrder.get("userReceiveAddress") + "++++++" + bulkOrder.get("deliveryTime"));
                    if (numList.size() != 0) {
                        Intent ointent = new Intent(context, OrderChangeAct.class);
                        ointent.putExtra("productDetailCart", productDetailCart);
                        ointent.putExtra("addressId", bulkOrder.get("userReceiveAddress"));
                        ointent.putExtra("productId", productId);
                        ointent.putExtra("productName", productName);
                        ointent.putExtra("requiredExplain", bulkOrder.get("requiredExplain"));
                        ointent.putExtra("deliveryTime", bulkOrder.get("deliveryTime"));
                        ointent.putExtra("deliveryWay", bulkOrder.get("deliveryWay"));
                        ointent.putExtra("productType", productType);
                        ointent.putExtra("productimgUrl", productimgUrl);
                        startActivity(ointent);
                    }
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getDealException(HttpException httpException, String result) {
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {
                if (!pd.isShowing())
                    pd.show();

            }
        };
        xutilsPost.doPostqueryShoppingCartRecords(context, id, ioAuthCallBack);
    }

    public void loadProductDetail(String pid) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {
                    productdata = Tool.getMapByJsonObj(result);
                    productType = productdata.get("productType");
                    productName = productdata.get("productName");
                    productDetailCart.setMinOrderNumber(ParseUtils.string2int(productdata.get("minOrderNumber")));
                    productDetailCart.setOptOrderNumber(ParseUtils.string2int(productdata.get("optOrderNumber")));
                    productDetailCart.setMinquotation(ParseUtils.string2float(productdata.get("quotation")));
                    productDetailCart.setOptquotation(ParseUtils.string2float(productdata.get("quotation2")));
                    loadqueryShoppingCartRecords(id);
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getDealException(HttpException httpException, String result) {
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {
                if (!pd.isShowing())
                    pd.show();
            }
        };
        xutilsPost.doPostProductDetail(context, pid, ioAuthCallBack);
    }
}
